package com.y.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.y.config.exception.AccountLoginException;
import com.y.entity.Role;
import com.y.entity.User;
import com.y.entity.vo.R;
import com.y.entity.vo.RHttpStatusEnum;
import com.y.service.UserService;
import com.y.utils.ConstantName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: Yjh
 */
@Controller
public class LoginController {


    @Autowired
    UserService userService;


    @RequestMapping("/index")
    public String toIndex(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 验证码
     * @param response
     * @param session
     * @throws Exception
     */
    @RequestMapping("/createVerifyCode")
    public void createVerifyCode(HttpServletResponse response, HttpSession session) throws Exception{
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 100);
        String code = captcha.getCode();
        // 将验证码存入session
        session.setAttribute(ConstantName.CAPTCHA,code);
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        System.out.println("验证码为:  "+code);
        outputStream.close();
    }


    /**
     * 登录
     * @param loginUser 登录实体
     * @param captcha  验证码
     * @return 视图名称
     */
    @RequestMapping("/login")
    public String login(User loginUser, @RequestParam(value = "captcha",defaultValue = "null") String captcha, HttpSession session){
        String code = (String)session.getAttribute(ConstantName.CAPTCHA);

        if ( captcha == null || !captcha.equals(code) ){
            throw new AccountLoginException(RHttpStatusEnum.CAPTCHA_ERROR);
        }
        // 登录
        User user = userService.login(loginUser);

        for (Role role : user.getRoles()) {
            if (role.getName().contains("admin")) return "redirect:/index"; // 管理界面
        }
        return "front/index";

    }


    /**
     * 登出
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        StpUtil.logout();
        return "login";
    }

    @RequestMapping("/check/isLogin")
    @ResponseBody
    public R checkLogin(){
        return StpUtil.isLogin() ? R.success() : R.error();
    }


    @RequestMapping("/console")
    public String console(){
        return "view/console/console2";
    }


}
